package com.un.web.sys.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Page;
import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageInfo;
import com.un.core.common.R;
import com.un.web.sys.domain.entity.SysRole;
import com.un.web.sys.domain.entity.SysUser;
import com.un.web.sys.domain.vo.SysUserVO;
import com.un.web.sys.service.SysUserService;
import com.un.core.utils.ConvertUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * (sys_user)表控制层
 *
 * @author xxxxx
 */
@RestController
@RequestMapping("sys")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;


    @PostMapping("loginOut")
    public R loginOut(Integer id){
        sysUserService.loginOut(id);
        return R.success();
    }

    @PostMapping("login")
    public R loginUser(@RequestBody SysUser user){

        if (StrUtil.isBlankIfStr(user.getMobile())||StrUtil.isBlankIfStr(user.getPassword())){
            return R.error("用户或密码不能为空");
        }
        HashMap<String, Object> result = sysUserService.login(user);
        if (result.size()<2){
            return R.error(result.get("msg").toString());
        }
        return R.success(result);
    }
    @GetMapping("wx/login")
    public R wxLogin(String temUserId){
        HashMap<String, Object> result = sysUserService.loginWx(temUserId);
        if (StrUtil.isEmptyIfStr(result)){
            return R.error("登陆超时");
        }
        return R.success(result);
    }

    @GetMapping("wx")
    public R getCode(){
        HashMap qrCode = sysUserService.getQrCode();
        return R.success(qrCode);
    }


    @GetMapping("getUser")
    public R selectOne(Integer id) {
        SysUser data = sysUserService.selectByPrimaryKey(id);
        if (StrUtil.isEmptyIfStr(data)) {
            return R.error(405, "数据不存在");
        }
        return R.success(data);
    }

    @PostMapping("saveUser")
    public R addUser(@RequestBody SysUser sysUser) {
        if (StrUtil.isEmptyIfStr(sysUser.getName())) {
            return R.error("插入失败");
        }
        if (sysUserService.saveUser(sysUser)) {
            return R.success();
        }
        return R.error("用户名已存在");
    }


    @DeleteMapping("delUser/{id}")
    public R delUser(@PathVariable Integer id){
        SysUser sysUser = sysUserService.selectByPrimaryKey(id);
        if (sysUser.getRoleId()==1||sysUser.getName().equals("admin")){
            return R.error("不能删除管理员");
        }
        sysUserService.deleteByPrimaryKey(id);
        return R.success();
    }

    @GetMapping("getUserAll")
    public R userAll(Page page, String name) {
        SysUser sysUser = new SysUser();
        sysUser.setName(name);
        PageInfo<SysUserVO> data = sysUserService.selectAllByPage(page, sysUser);
        return R.success(data);
    }
}